const getExactViewData = function(pointData, pId, ruleMap) {
	let {
		all_count,
		can_count,
		can_devices,
		used_devices,
		lock_devices,
		unitMap,
		AMap,
		BMap,
		ABMap,
		D7List
	} = pointData;
	
	if(!unitMap) unitMap = new Map();
	if(!AMap) AMap = new Map();
	if(!BMap) BMap = new Map();
	if(!ABMap) ABMap = new Map();
	if(!D7List) D7List = [];

	let resultList = [],
		count = 0;

	// 数据结构含有层级
	// 0、-1：1层（-1为AB面专用）
	// 1：2层
	// 2：3层
	let type;
	const genResultDevice = function(device, type = 0, deviceB) {
		if (type == -1) {
			return {
				id: device.id + '_' + deviceB.id,
				name: device.address + '+B面',
				isLeaf: false,
				level: 1,
				ruleId: 6,
				list: [{
						id: device.id,
						level: 2,
						name: device.address,
						isLeaf: true,
						obj: device
					},
					{
						id: deviceB.id,
						level: 2,
						name: deviceB.address,
						isLeaf: true,
						obj: deviceB
					}
				]
			}
		}
		if (type == 0) {
			return {
				id: device.id,
				level: 1,
				name: device.address,
				isLeaf: true,
				obj: device
			}
		}
		if (type == 1) {
			return {
				id: device.id,
				name: device.address,
				level: 2,
				isLeaf: true,
				obj: device
			};
		}
		if (type == 2) {
			return {
				id: device.id,
				level: 3,
				name: device.address,
				isLeaf: true,
				obj: device
			}
		}
	};
	const getNums = function(key, list) {
		const nums = key.split('_');
		let building_num = '',
			unit_num = '',
			floor_num = '',
			door_num = '',
			rail_num = '';
		if (nums.length >= 2) {
			building_num = nums[0];
			unit_num = nums[1];
		}
		if (nums.length >= 3) {
			floor_num = nums[2];
		}
		if (nums.length >= 4) {
			door_num = nums[3];
		}
		if (nums.length >= 5) {
			rail_num = nums[4];
		}
		const id = ['p', ...(list || []).map(d => d.id)].join('_');
		const name1 = building_num + '号楼' + unit_num + '单元' + (floor_num ? (floor_num + '层') : '');
		return {
			building_num,
			unit_num,
			floor_num,
			door_num,
			rail_num,
			id,
			name1,
		};
	};
	const getAddress = function(d, type, hasFeature=false){
		return type==1?(d.floor + (!!hasFeature?('_' + d.media_feature):'') + '_' + d.code):
		((!!hasFeature?('_' + d.media_feature):'') + '_' + d.code);
	};
	if (ruleMap.size > 0) {
		if (!!ruleMap.get('1') || !!ruleMap.get('4') || !!ruleMap.get('5') || !!ruleMap.get('6')) {
			// 小区数量上限、A面、B面、AB面
			type = 0;
			if (!!ruleMap.get('1') && !ruleMap.get('4') && !ruleMap.get('5') && !ruleMap.get('6')) {
				resultList = (can_devices || []).map(d => (genResultDevice(d, 0)));
				count = resultList.length;
			}
			if (!!ruleMap.get('4')) {
				for (let list of AMap.values()) {
					resultList = [...resultList, ...((list || []).map(d => (genResultDevice(d, 0))))];
				}
				count = resultList.length;
			}
			if (!!ruleMap.get('5')) {
				for (let list of BMap.values()) {
					resultList = [...resultList, ...((list || []).map(d => (genResultDevice(d, 0))))];
				}
				count = resultList.length;
			}
			if (!!ruleMap.get('6')) {
				for (let {
						a,
						b
					} of ABMap.values()) {
					resultList.push(genResultDevice(a, -1, b));
				}
				count = resultList.length * 2;
			}
		}
		if (!!ruleMap.get('7') && !ruleMap.get('2') && !ruleMap.get('3')) {
			// 仅指定楼层
			type = 0;
			resultList.push(...((D7List || []).map(d => (genResultDevice(d, 0)))));
			count = resultList.length;
		}
		if (!!ruleMap.get('2') && !ruleMap.get('7') && !ruleMap.get('3')) {
			// 仅指定单元数量上限
			type = 1;
			unitMap.forEach((floorMap, unitKey) => {
				let max = 0,
					deviceList = [];
				floorMap.forEach((dlist, floorKey) => {
					count += dlist.length;
					deviceList.push(...((dlist || []).map(d => (genResultDevice(
						Object.assign(d, {
							// address: d.floor + '_' + d.media_feature + '_' + d.code
							address: getAddress(d, 1)
						}), 1)))));
				});
				if ((deviceList.length || 0) > 0) {
					const {
						id,
						name1
					} = getNums(unitKey, deviceList);
					max = Math.min(parseInt(ruleMap.get('2').n || 0), deviceList.length || 0);
					resultList.push({
						id: id,
						name: name1,
						level: 1,
						isLeaf: false,
						max: max,
						list: deviceList
					});
				}
			})
		}
		if (!!ruleMap.get('3') && !ruleMap.get('7') && !ruleMap.get('2')) {
			// 仅指定楼层数量上限
			type = 1;
			unitMap.forEach((floorMap, unitKey) => {
				floorMap.forEach((dlist, floorKey) => {
					count += dlist.length;
					let deviceList = ((dlist || []).map(d => (genResultDevice(
						Object.assign(d, {
							// address: d.media_feature + '_' + d.code
							address: getAddress(d, 2)
						}), 1))));
					if ((deviceList.length || 0) > 0) {
						const {
							id,
							name1
						} = getNums(unitKey + '_' + floorKey, deviceList);
						let max = Math.min(parseInt(ruleMap.get('3').n || 0), deviceList.length ||
							0);
						resultList.push({
							id: id,
							name: name1,
							level: 1,
							isLeaf: false,
							max: max,
							list: deviceList
						});
					}
				});
			})
		}
		if (!!ruleMap.get('2') && !!ruleMap.get('7') && !ruleMap.get('3')) {
			// 指定单元数量上限、指定楼层
			type = 1;
			unitMap.forEach((floorMap, unitKey) => {
				let max = 0,
					deviceList = [];
				floorMap.forEach((dlist, floorKey) => {
					if (ruleMap.get('7').appoint.indexOf(floorKey) > -1) {
						count += dlist.length;
						deviceList.push(...((dlist || []).map(d => (genResultDevice(
							Object.assign(d, {
								// address: d.floor + '_' + d.media_feature + '_' + d.code
								address: getAddress(d, 1)
							}), 1)))));
					}
				});
				if ((deviceList.length || 0) > 0) {
					const {
						id,
						name1
					} = getNums(unitKey, deviceList);
					max = Math.min(parseInt(ruleMap.get('2').n || 0), deviceList.length || 0);
					resultList.push({
						id: id,
						name: name1,
						level: 1,
						isLeaf: false,
						max: max,
						list: deviceList
					});
				}
			})
		}
		if (!!ruleMap.get('3') && !!ruleMap.get('7') && !ruleMap.get('2')) {
			// 指定楼层数量上限、指定楼层
			type = 1;
			unitMap.forEach((floorMap, unitKey) => {
				floorMap.forEach((dlist, floorKey) => {
					if (ruleMap.get('7').appoint.indexOf(floorKey) > -1) {
						count += dlist.length;
						let deviceList = ((dlist || []).map(d => (genResultDevice(
							Object.assign(d, {
								// address: d.media_feature + '_' + d.code,
								address: getAddress(d, 2)
							}), 1))))

						if ((deviceList.length || 0) > 0) {
							const {
								id,
								name1
							} = getNums(unitKey + '_' + floorKey, deviceList);
							let max = Math.min(parseInt(ruleMap.get('3').n || 0), deviceList
								.length || 0);
							resultList.push({
								id: id,
								name: name1,
								level: 1,
								isLeaf: false,
								max: max,
								list: deviceList
							});
						}

					}
				});
			})
		}
		if (!!ruleMap.get('2') && !!ruleMap.get('3') && !ruleMap.get('7')) {
			// 指定单元数量上限、指定楼层数量上限
			type = 2;
			unitMap.forEach((floorMap, unitKey) => {
				let max = 0,
					unitList = [],
					unitCount = 0;
				floorMap.forEach((dlist, floorKey) => {
					count += dlist.length;
					let deviceList = ((dlist || []).map(d => (genResultDevice(
						Object.assign(d, {
							// address: d.media_feature + '_' + d.code,
							address: getAddress(d, 2)
						}), 1))))

					if ((deviceList.length || 0) > 0) {
						const {
							id
						} = getNums(unitKey + '_' + floorKey, deviceList);
						let innermax = Math.min(parseInt(ruleMap.get('3').n || 0), deviceList
							.length || 0);
						unitCount += max;
						unitList.push({
							id: id,
							name: floorKey + '层',
							level: 2,
							isLeaf: false,
							max: innermax || 0,
							list: deviceList
						});
					}

				});
				if ((unitList.length || 0) > 0) {
					const {
						id,
						name1
					} = getNums(unitKey, unitList);
					max = Math.min(parseInt(ruleMap.get('2').n || 0), unitCount);
					resultList.push({
						id: id,
						name: name1,
						level: 1,
						isLeaf: false,
						max: max,
						list: unitList
					});
				}
			})
		}
		if (!!ruleMap.get('2') && !!ruleMap.get('3') && !!ruleMap.get('7')) {
			// 指定单元数量上限、指定楼层数量上限、指定楼层
			type = 2;
			unitMap.forEach((floorMap, unitKey) => {
				let max = 0,
					unitList = [],
					unitCount = 0;
				floorMap.forEach((dlist, floorKey) => {
					if (ruleMap.get('7').appoint.indexOf(floorKey) > -1) {
						count += dlist.length;
						let deviceList = ((dlist || []).map(d => (genResultDevice(
							Object.assign(d, {
								// address: d.media_feature + '_' + d.code,
								address: getAddress(d, 2)
							}), 1))))

						if ((deviceList.length || 0) > 0) {
							const {
								id
							} = getNums(unitKey + '_' + floorKey, deviceList);
							let innermax = Math.min(parseInt(ruleMap.get('3').n || 0), deviceList
								.length || 0);
							unitCount += max;
							unitList.push({
								id: id,
								name: floorKey + '层',
								level: 2,
								isLeaf: false,
								max: innermax || 0,
								list: deviceList
							});
						}

					}
				});

				if ((unitList.length || 0) > 0) {
					const {
						id,
						name1
					} = getNums(unitKey, unitList);
					max = Math.min(parseInt(ruleMap.get('2').n || 0), unitCount);
					resultList.push({
						id: id,
						name: name1,
						level: 1,
						isLeaf: false,
						max: max,
						list: unitList
					});
				}
			})
		}

	} else {
		type = 0;
		resultList = (can_devices || []).map(d => (genResultDevice(d, 0)));
		count = resultList.length;
	}

	return {
		list: resultList,
		count
	}
};

const getOriginData = function(firstResults, point_type_ids, combo_ids) {
	return JSON.parse(JSON.stringify(firstResults || [])).filter(d => {
		// let deviceCount = 0;
		// for (const p of Object.keys(d.points || {})) {
		// 	if (!!p) {
		// 		deviceCount += (d.points['' + p].all_count || 0);
		// 	}
		// }
		// return deviceCount > 0;
		let flag = false;
		const keys = Object.keys(d.points) || [];
		keys.forEach(key => {
			flag = flag || ((d.points[key].can_devices || []).length > 0);
		})
		return flag;
	}).map(d => {
		d.to = {};
		d.combo_to = {};
		d.to_exact = {};
		point_type_ids.forEach(id => {
			d.to['' + id] = 0;
			d.to_exact['' + id] = [];
		});
		combo_ids.forEach(id => {
			d.combo_to['' + id] = 0;
		});
		// 设置可分配数，可以由规则变换
		const pIds = Object.keys(d.points || {}) || [];
		pIds.forEach(pId => {
			d.points['' + pId].can_count = (d.points['' + pId].can_devices || []).length;
		});
		return d;
	});
};

const generateDeviceKey = function(device) {
	const buildingkey = '' + (device.building_number != null ? device.building_number : '');
	const unitKey = buildingkey + '_' + (device.unit_number != null ? device.building_number : '');
	const floorKey = unitKey + '_' + (device.floor != null ? device.building_number : '');
	const doorKey = floorKey + '_' + (device.door_number != null ? device.door_number : '');
	const railKey = doorKey + '_' + (device.rail_number != null ? device.rail_number : '');
	return {
		buildingkey,
		unitKey,
		floorKey,
		doorKey,
		railKey
	}
};

const filterDistTableData = function(origin_data, activeRuleMap) {
	return origin_data
		.map(item => {
			let row = JSON.parse(JSON.stringify(item));
			const pIds = Object.keys(row.points) || [];
			if (pIds.length > 0) {
				pIds.forEach(pId => {
					const can_devices = row.points['' + pId].can_devices || [];
					const ruleMap = activeRuleMap.get('' + pId) || new Map();
					if (can_devices.length > 0 && ruleMap.size > 0) {
						let min = 0;
						let ruleLimitList = [];

						let unitMap = new Map();
						let AMap = new Map();
						let BMap = new Map();
						let ABMap = new Map();
						let D7List = [];

						can_devices.forEach(device => {
							const {
								unitKey,
								railKey
							} = generateDeviceKey(device);
							if ('' + pId === '122' || '' + pId === '123' || '' + pId ===
								'125' || '' + pId === '129') {
								if (!!unitKey) {
									let floorMap = unitMap.get(unitKey) || new Map();
									if (!!device.floor) {
										const floor = '' + device.floor;
										let list = floorMap.get(floor) || [];
										list.push(device);
										floorMap.set(floor, list);
									}
									unitMap.set(unitKey, floorMap);
								}
							}
							if ('' + pId === '127' || '' + pId === '128' || '' + pId ===
								'135') {
								if ((device.media_feature || '').indexOf('A面') > -1) {
									if (!!railKey) {
										let list = AMap.get(railKey) || [];
										list.push(device);
										AMap.set(railKey, list);
									}
								}
								if ((device.media_feature || '').indexOf('B面') > -1) {
									if (!!railKey) {
										let list = BMap.get(railKey) || [];
										list.push(device);
										BMap.set(railKey, list);
									}
								}
							}
						});
						if (AMap.size > 0 && BMap.size > 0) {
							AMap.forEach(function(aList, key) {
								if (aList.length > 0) {
									const bList = BMap.get(key) || [];
									if (bList.length > 0) {
										ABMap.set(key, {
											a: aList[0],
											b: bList[0]
										});
									}
								}
							});
						}
						// 过滤
						ruleMap.forEach(function(rule, ruleId) {
							if ('' + ruleId === '1') { // 一小区n个
								ruleLimitList.push(Math.min(can_devices.length, parseInt(rule
									.n || 0)));
							}
							if ('' + ruleId === '2') { // 一单元n个
								let resultCount = 0;
								let limitCount = parseInt(rule.n || 0);
								for (let floorMap of unitMap.values()) {
									let c = 0;
									for (let ds of floorMap.values()) {
										c += ds.length || 0;
									}
									resultCount += (c < limitCount ? c : limitCount);
								}
								ruleLimitList.push(resultCount);
							}
							if ('' + ruleId === '3') { // 一层1个
								let resultCount = 0;
								for (let floorMap of unitMap.values()) {
									resultCount += (floorMap.size || 0);
								}
								ruleLimitList.push(resultCount);
							}
							if ('' + ruleId === '4') { // A面
								let resultCount = AMap.size || 0;
								ruleLimitList.push(resultCount);
							}
							if ('' + ruleId === '5') { // B面
								let resultCount = BMap.size || 0;
								ruleLimitList.push(resultCount);
							}
							if ('' + ruleId === '6') { // A面+B面
								let resultCount = ABMap.size || 0;
								ruleLimitList.push(resultCount * 2);
							}
							if ('' + ruleId === '7') { // 指定楼层
								let resultCount = 0;
								let can = 0;
								let limitFloors = (rule.appoint || []).map(a => ('' + a));
								for (let floorMap of unitMap.values()) {
									let unitCan = 0;
									const unitLimit = parseInt(ruleMap.get('2').n || -1);
									for (let ds of floorMap.values()) {
										let temp = (ds || []).filter(d => (limitFloors
											.indexOf('' + d.floor) > -1));
										if(temp.length>0){
											if(!!ruleMap.get('3')) {
												if(unitLimit == -1){
													can++;
												}else{
													if(unitCan < unitLimit){
														can++;
														unitCan++;
													}
												}
											}else{
												if(unitLimit == -1){
													can+=temp.length;
												}else{
													if(unitCan < unitLimit){
														if((unitCan+temp.length) <= unitLimit){
															can+=temp.length;
															unitCan+=temp.length;
														}else{
															const sub = (unitCan+temp.length) - unitLimit;
															can+=sub;
															unitCan+=sub;
														}
													}
												}
											}
										}
										D7List.push(...temp);
									}
								}
								resultCount = can;
								ruleLimitList.push(resultCount);
							}
						});
						//console.log(row.name, pId, ruleLimitList);
						row.points['' + pId].can_count = Math.min(row.points['' + pId].can_count || 0,
							...ruleLimitList);
						row.points['' + pId].unitMap = unitMap;
						row.points['' + pId].AMap = AMap;
						row.points['' + pId].BMap = BMap;
						row.points['' + pId].ABMap = ABMap;
						row.points['' + pId].D7List = D7List;
					}
				});
			}
			//console.log(row);
			return row;
		});
};

export default {
	getExactViewData,
	getOriginData,
	filterDistTableData
}
